package com.hb.trans.global

import android.content.Context
import android.graphics.Bitmap
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import org.jetbrains.anko.dip
import java.lang.ref.WeakReference
import java.security.MessageDigest

class RoundRadiusCrop(context: Context, var roundRadius: Int) : BitmapTransformation() {

    private lateinit var contextWeakReference: WeakReference<Context>

    init {
        contextWeakReference = WeakReference(context)
    }

    private val VERSION = 1
    private val ID = "com.bumptech.glide.load.resource.bitmap.RoundRadiusCrop.$VERSION"
    private val ID_BYTES = ID.toByteArray(Key.CHARSET)

    override fun transform(
        pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int
    ): Bitmap {
        val result = contextWeakReference.get()?.let {
            TransformationUtils.roundedCorners(pool, toTransform, it.dip(roundRadius))
        }
        return result ?: toTransform
    }

    override fun equals(o: Any?): Boolean {
        return o is CircleCrop
    }

    override fun hashCode(): Int {
        return ID.hashCode()
    }

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }
}